/*
 * @Description: 
 * @Author: chenjiaxin
 * @Date: 2021-12-20 21:42:30
 * @LastEditTime: 2022-01-08 19:23:20
 * @FilePath: \novel-serve\src\controller\user.controller.js
 */
const jwt = require('jsonwebtoken');
const service = require("../service/user.service");
const errorTypes = require("../constants/error-types");
const { PRIVATE_KEY } = require("../app/config");
const { verifyEmail } = require("../utils/verify-handle");
const email = require("../utils/email");
const { EMAIL_FROM, EAMIL_SUBJECT } = require("../constants/email-options");
const { responseHandle } = require('../utils/tool');
class UserController {
  async createUser (ctx, next) {
    try {
      // 1、创建用户
      let { e_mail, password } = ctx.request.body;
      let result = await service.createUser({ e_mail, password });

      // 2、获取新用户信息
      const user = await service.getUserByEmail(e_mail);

      // 3、颁发token
      //颁发token
      const token = jwt.sign({ id: user.id, e_mail }, PRIVATE_KEY, {
        expiresIn: 24 * 60 * 60, // 一天
        algorithm: 'RS256'
      })

      delete user.password;
      // let data = {
      //   code: 200,
      //   data: {
      //     user,
      //     token
      //   },
      // }
      // ctx.body = data;
      ctx.body = responseHandle(200, {user, token});

    } catch (error) {

      return ctx.app.emit('error', errorTypes.SYNTAX_ERROR, ctx, error.message);
    }
  }

  async getEmailCode (ctx, next) {
    try {
      const { e_mail } = ctx.request.query;
      if (!verifyEmail(e_mail)) {
        return ctx.app.emit("error", errorTypes.E_MAIL_ERROR, ctx);
      }

      //发送code 到用户邮箱
      const code = await email.getCode();
      console.log("验证码是：", code);
      
      //发送邮箱的信息，内容配置
      let mailOptions = {
          from: EMAIL_FROM, // sender address
          to: e_mail,                      // list of receivers  发送的谁
          subject: EAMIL_SUBJECT,      // Subject line
          // text: '验证码：' + code, // plain text body   内容
          text: "发送的内容~~~",
          html: `【大橘网】验证码：${code}, 15分钟内输入有效`,
      };
      
      try {

        let trans = await email.transporter();
        await new Promise((resolve, reject) => {
          trans.sendMail(mailOptions, (err) => {
            if (err) {
              console.log("发送失败", err);
              reject(err);
            } else {
              console.log("发送成功");
              resolve();
            }
          });
        });
        
        //把目标邮箱  和 验证码 保存到seesion中
        ctx.session.emailInfo = {
          e_mail,
          code,
        };
        console.log("====", ctx.session);
  
        // ctx.body = {
        //   code: 200,
        //   data: {
        //     data: "发送成功"
        //   }
        // }
        ctx.body = responseHandle(200, "发送成功");

        // ctx.session = {};
        // ctx.session = {
        //   e_mail,
        //   code
        // };
        
        
      } catch (error) {
        console.log(error);
        return ctx.app.emit('error', errorTypes.SYNTAX_ERROR, ctx, error.message);
      }
      

    } catch (error) {
      console.log(error);
      return ctx.app.emit('error', errorTypes.SYNTAX_ERROR, ctx, error.message);
    }
    
  }
}

module.exports = new UserController();
